<template>
    <div class="plan01">
        <CrTitle>路线规划</CrTitle>
        <div class="select-mode">
            <span>规划模式:</span>
            <el-select v-model="selectMode" placeholder="请选择模式">
                <el-option label="最快捷模式" value="0"></el-option>
                <el-option label="最经济模式" value="1"></el-option>
                <el-option label="最短距离模式" value="2"></el-option>
                <el-option label="考虑实时路况" value="4"></el-option>
            </el-select>
        </div>
        <div class="guihau-box">
            <i class="el-icon-sort icon-sort"></i>
            <div class="serach-start">
                <el-autocomplete
                        class="cr-el-autocomplete-2"
                        v-model="searchStartStr"
                        :fetch-suggestions="querySearchAsync"
                        placeholder="请输入内容"
                        @select="handleStartSelect">
                    <template #prepend>起点</template>
                </el-autocomplete>
            </div>
            <ul class="list-box">
                <li v-for="item in datasList" class="list-box-item" @click="itemClickHandler(item)">
                    <span>避障点:{{ item }}</span>
                    <i class="el-icon-remove-outline remove-icon" @click.stop="deleteItem(item)"></i>
                </li>
            </ul>
            <div class="serach-end">
                <i class="el-icon-circle-plus-outline add-icon" @click="addBiZhang"></i>
                <el-autocomplete
                        class="cr-el-autocomplete-2"
                        v-model="searchEndStr"
                        :fetch-suggestions="querySearchAsync"
                        placeholder="请输入内容"
                        @select="handleEndSelect">
                    <template #prepend>终点</template>
                </el-autocomplete>
            </div>
        </div>
        <div class="driving-btn" @click="startDriving">
            开始规划
        </div>
    </div>
    <div class="panel03">
        <CrTitle>实时天气</CrTitle>
        <ul>
            <li><span>城市:</span>{{reatWeather.city}}</li>
            <li><span>天气:</span>{{reatWeather.weather}}</li>
            <li><span>温度:</span>{{reatWeather.temperature}}℃</li>
            <li><span>风向:</span>{{reatWeather.windDirection}}</li>
            <li><span>风力:</span>{{reatWeather.windPower}}级</li>
            <li><span>空气湿度:</span>{{reatWeather.humidity}}</li>
            <li><span>发布时间:</span>{{reatWeather.reportTime}}</li>
        </ul>
    </div>
    <div class="plan02">
        <div class="legend-box">
            <div class="legend">
                <span>畅通</span>
                <ul>
                    <li style="background-color: #34b000;"></li>
                    <li style="background-color: #fecb00;"></li>
                    <li style="background-color: #df0100;"></li>
                    <li style="background-color: #8e0e0b;"></li>
                </ul>
                <span>拥堵</span>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
    import CrTitle from "../../components/CrTitle.vue";
    import {onUnmounted, ref} from 'vue'
    import {AMapUtil} from "../../utils/AMapUtil";
    import {GlobalVariables} from "../../GlobalVariables";
    import {ElMessage} from 'element-plus'
    import {JsUtil} from "../../utils/JsUtil";
    import {AxiosCtrl} from "../../axios";

    const datasList: any = ref([]);//避障点数据
    let placeSearchOverlayGroups: any = null;
    let biZhagnIndex = 0;
    let driving: any = null;
    const selectMode = ref("0");//选择模式
    const searchStartStr = ref("");//搜索起点字符串
    const searchEndStr = ref("");//搜索终点字符串
    const reatWeather = ref({
        city: "",
        adcode: "",
        weather: "",
        temperature: "",
        windDirection: "",
        windPower: "",
        humidity: "",
        reportTime: "",
    });//天气
    let startP: any = null, endP: any = null;

    async function querySearchAsync(queryString: string, cb: any) {
        console.log(queryString)
        if (!queryString) {
            cb([]);
            return;
        }
        const pois = await AxiosCtrl.searchByStr(queryString);
        const results = pois.map((item: any) => {
            return {
                value: item.name,
                location: item.location
            };
        });
        cb(results);
    }

    function handleStartSelect(item: any) {
        startP = item;
    }

    function handleEndSelect(item: any) {
        endP = item;
    }

    function startDriving() {
        if (startP == null) {
            ElMessage.error("请先输入起点");
            return;
        }
        if (endP == null) {
            ElMessage.error("请先输入终点");
            return;
        }
        const all = placeSearchOverlayGroups.getOverlays();
        const paths = datasList.value.map((item: any) => {
            const index = datasList.value.indexOf(item);
            const lngLat = all[index].getPosition()
            return [
                new AMap.LngLat(lngLat.lng - 0.004, lngLat.lat + 0.004),
                new AMap.LngLat(lngLat.lng + 0.004, lngLat.lat + 0.004),
                new AMap.LngLat(lngLat.lng + 0.004, lngLat.lat - 0.004),
                new AMap.LngLat(lngLat.lng - 0.004, lngLat.lat - 0.004)
            ];//`${lngLat.lng},${lngLat.lat}`;
        });
        queryDriving(startP.location.split(","), endP.location.split(","), parseInt(selectMode.value), paths)
    }

    //路线规划
    function queryDriving(sp: any, ep: any, policy = AMap.DrivingPolicy.LEAST_FEE, path: Array<any>) {
        if (driving == null) {
            // 构造路线导航类
            driving = new AMap.Driving({
                ferry: 1, // 是否可以使用轮渡
                map: GlobalVariables.map,
                autoFitView: false
            });
        }
        driving.setPolicy(policy);
        if (path.length > 0) {
            driving.setAvoidPolygons(path);
        }
        driving.search(sp, ep, function (status: any, result: any) {
            if (status === 'complete') {
                if (result.routes && result.routes.length) {
                    ElMessage.success('绘制驾车路线完成')
                }
            } else {
                ElMessage.error('获取驾车数据失败：' + result)
            }
        });
    }

    //添加避障点
    function addBiZhang() {
        biZhagnIndex++;
        const dragMarker: any = new AMap.Marker({
            position: GlobalVariables.map.getCenter(),
            icon: new AMap.Icon({
                image: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
                size: new AMap.Size(22, 28),  //图标所处区域大小
                imageSize: new AMap.Size(22, 28) //图标大小
            }),
            offset: new AMap.Pixel(-11, -28),
            draggable: true, // 设置是否可以拖拽
            cursor: 'move',
            raiseOnDrag: true, // 设置拖拽效果
        });
        // dragMarker.on("dragend",(res:any)=>{
        //   ruleForm.value.position = [res.lnglat.lng, res.lnglat.lat];
        // });
        datasList.value.push(biZhagnIndex);
        placeSearchOverlayGroups.addOverlay(dragMarker);
    }

    //点击避障点
    function itemClickHandler(item: number) {
        const index = datasList.value.indexOf(item);
        const all = placeSearchOverlayGroups.getOverlays();
        GlobalVariables.map.setZoomAndCenter(18, all[index].getPosition());
    }

    //删除避障点
    function deleteItem(item: any) {
        const index = datasList.value.indexOf(item);
        datasList.value.splice(index, 1)
        const all = placeSearchOverlayGroups.getOverlays();
        placeSearchOverlayGroups.removeOverlay(all[index]);
    }

    //清空数据
    function removeData() {
        if (placeSearchOverlayGroups) {
            GlobalVariables.map.remove(placeSearchOverlayGroups);
        }
    }


    function setWeather() {
        AMap.plugin('AMap.Weather', function () {
            var weather = new AMap.Weather();
            //查询实时天气信息, 查询的城市到行政级别的城市，如朝阳区、杭州市
            weather.getLive('福州市', function (err: any, data: any) {
                if (err) {
                    ElMessage.error("实时天气获取失败!");
                    return;
                }
                reatWeather.value = data;
            });
        });
    }


    AMapUtil.onMapLoaded(() => {
        AMapUtil.showTraffic();
        GlobalVariables.map.setZoomAndCenter(14, GlobalVariables.curPosition);
        placeSearchOverlayGroups = new AMap.OverlayGroup([]);
        GlobalVariables.map.add(placeSearchOverlayGroups)
        setWeather();
    })

    onUnmounted(() => {
        AMapUtil.hideTraffic();
        if (driving != null) {
            driving.clear();
        }
        removeData();
    })
</script>

<style scoped lang="less">
    .plan01 {
        position: fixed;
        top: 1rem;
        left: 1.05rem;
        width: 3.5rem;
        background-color: #304a4f;

        .select-mode {
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 0.1rem 0;

            span {
                font-size: 0.14rem;
                padding-right: 0.1rem;
            }
        }

        .guihau-box {
            position: relative;
            top: 0;
            left: 0;
            width: 100%;
            padding: 0.1rem 0.35rem;
            box-sizing: border-box;

            .icon-sort {
                position: absolute;
                top: 50%;
                left: 0.1rem;
                margin-top: -0.1rem;
                box-sizing: border-box;
                font-size: 0.2rem;
            }

            .serach-start {
                margin-bottom: 0.1rem;
            }

            .list-box {
                .list-box-item {
                    position: relative;
                    top: 0;
                    left: 0;
                    cursor: pointer;
                    padding: 0.1rem 0.2rem;
                    border-bottom: 0.01rem solid #1e2d2e;

                    &:hover {
                        background-color: #1e2d2e;
                    }

                    .remove-icon {
                        position: absolute;
                        top: 0.1rem;
                        right: -0.25rem;
                        box-sizing: border-box;
                        font-size: 0.2rem;
                        cursor: pointer;
                    }
                }
            }

            .serach-end {
                margin-top: 0.1rem;
                position: relative;
                top: 0;
                left: 0;

                .add-icon {
                    position: absolute;
                    top: 0.1rem;
                    right: -0.25rem;
                    box-sizing: border-box;
                    font-size: 0.2rem;
                    cursor: pointer;
                }
            }
        }

        .driving-btn {
            text-align: center;
            font-size: 0.16rem;
            line-height: 0.4rem;
            width: 80%;
            border-radius: 0.05rem;
            margin: 0 auto;
            margin-bottom: 0.15rem;
            background-color: #1f2e30;
            color: #deecff;
            cursor: pointer;
            border: 0.01rem solid #000;

            &:hover {
                border: 0.01rem solid #4a919b;
                background-color: #2d5157;
            }
        }

    }

    .plan02 {
        position: fixed;
        bottom: 1rem;
        right: 0.2rem;
        background-color: #304a4f;

        .legend-box {
            padding: 0 0.1rem;
            display: flex;
            justify-content: center;

            .legend {
                display: flex;
                align-items: center;
                justify-content: center;

                ul {
                    display: flex;
                    align-items: center;
                    padding: 0 0.1rem;

                    li {
                        width: 0.2rem;
                        height: 0.05rem;
                        background-color: #fff;
                        border-radius: 0.01rem;
                        margin: 0 0.01rem;
                    }
                }
            }
        }
    }

    .panel03 {
        position: fixed;
        top: 1rem;
        right: 0.2rem;
        width: 3.5rem;
        background-color: #304a4f;
        ul {
            padding: 0 0.2rem;
            li {
                padding: 0.05rem;
                span {
                    padding-right: 0.3rem;
                }
            }
        }
    }
</style>
